package com.aurora.service.impl;

import com.aurora.config.MqttConfig;
import com.aurora.dao.MessageInfoDao;
import com.aurora.entity.MessageInfo;
import com.aurora.model.dto.UserDetailsDTO;
import com.aurora.service.MessageInfoService;
import com.aurora.utils.UserUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * (MessageInfo)表服务实现类
 *
 * @author makejava
 * @since 2022-11-28 15:42:16
 */
@Service("messageInfoService")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class MessageInfoServiceImpl extends ServiceImpl<MessageInfoDao, MessageInfo> implements MessageInfoService {

    //引入MQTT配置类
    private final MqttConfig mqttConfig;
    //引入消息服务
    private final MessageInfoDao messageInfoDao;

    @Override
    public Page<MessageInfo> getChatRecord(String receiverId, Integer pageSize, Integer pageNum) {
        //得到当前登录的用户信息
        UserDetailsDTO userDetailsDTO = UserUtils.getUserDetailsDTO();
        //我发送的消息主题
        StringBuilder topicSelf = new StringBuilder();
        //主题为接收者id+发送者id+默认主题
        topicSelf.append(receiverId).append(userDetailsDTO.getUserInfoId()).append(mqttConfig.getDefaultTopic());
        //接收者发送的消息主题
        //主题为发送者id+接收者id+默认主题
        String topicReceiver = userDetailsDTO.getUserInfoId() + receiverId + mqttConfig.getDefaultTopic();
        //得到聊天记录
        Page<MessageInfo> page = this.page(new Page<>(pageSize, pageNum), new LambdaQueryWrapper<MessageInfo>()
                        .select(MessageInfo::getContent,MessageInfo::getTopic)
                .eq(MessageInfo::getTopic, topicSelf.toString())
                .or()
                .eq(MessageInfo::getTopic, topicReceiver)
                .orderByDesc(MessageInfo::getCreateTime)
        );
        page.getRecords().forEach(messageInfo -> {
            //如果主题为topicSelf.toString()，则是我发送的消息 设置字段isSelf为true
            //如果主题为topicReceiver.toString()，则是接收者发送的消息 设置字段isSelf为false
            messageInfo.setIsSelf(!messageInfo.getTopic().equals(topicSelf.toString()));
        });

        return page;
    }
}

